﻿using System;
using System.ComponentModel;
using System.Linq;
using ProjectEuler.Linq;

namespace ProjectEuler.Problems
{
    [EulerProblem(19, 171)]
    [Description("How many Sundays fell on the first of the month during the twentieth century?")]
    internal sealed class Problem019 : EulerProblem
    {
        public override Object Solve()
        {
            return (from y in (1901).To(2000)
                    from m in (1).To(12)
                    select ZellersCongruence(y, m, 1)).Count(d => d == DayOfWeek.Sunday);
        }

        private static DayOfWeek ZellersCongruence(Int32 year, Int32 month, Int32 day)
        {
            if (month < 3)
            {
                month += 12;
                year -= 1;
            }

            Int32 K;
            Int32 J = Math.DivRem(year, 100, out K);

            return (DayOfWeek)(
                (day + Math.Floor(2.6 * (month + 1.0))
                + K
                + Math.Floor(K / 4.0)
                + Math.Floor(J / 4.0)
                - (2 * J))
                % 7);
        }
    }
}
